﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;

namespace G.Reader.Controls
{
    public class FallingSnowBehavior : Behavior<Canvas>
    {
        private static Random randomNumber;



        protected override void OnAttached()
        {
            base.OnAttached();

            randomNumber = new Random();

            this.AssociatedObject.Loaded += new RoutedEventHandler(ApplicationLoaded);
        }

        void ApplicationLoaded(object sender, RoutedEventArgs e)
        {
            foreach (FrameworkElement element in this.AssociatedObject.Children)
            {
                FrameworkElement localCopy = element;

                double yPosition = Canvas.GetTop(localCopy);
                double xPosition = Canvas.GetLeft(localCopy);

                double speed = 2 * randomNumber.NextDouble();
                double counter = 0;
                double radius = 30 * speed * randomNumber.NextDouble();

                localCopy.Opacity = 0.2 + randomNumber.NextDouble();

                CompositionTarget.Rendering += delegate(object o, EventArgs arg)
                {
                    counter += Math.PI / (180 * speed);

                    if (yPosition < Application.Current.RootVisual.DesiredSize.Height)
                    {
                        yPosition += 0.2 + speed;
                    }
                    else
                    {
                        yPosition = -localCopy.Height;
                    }

                    Canvas.SetTop(localCopy, yPosition);
                    Canvas.SetLeft(localCopy, xPosition + radius * Math.Cos(counter));
                };
            }
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
        }
    }
}
